import refreshToken from '@/utils/refreshToken';
import { to } from 'await-to-js';
import { errorCode } from '@/utils/errorCode';
import { HttpStatus } from '@/enmus/RespEnum';
import { http, toast} from 'uview-plus'

const encryptHeader = 'encrypt-key';
export const globalHeaders = () => {
  return {
    Authorization: 'Bearer ' + getToken(),
    clientid: import.meta.env.VITE_APP_CLIENT_ID
  };
};
const initRequest = (vm) => {
  // 初始化请求配置
  http.setConfig((config: any) => {
    /* config 为默认全局配置*/
    config.baseURL = import.meta.env.VITE_APP_BASE_API; /* 根域名 */
    config.header['clientid'] = import.meta.env.VITE_APP_CLIENT_ID;
    config.timeout = 10000;
    return config;
  });

  // 请求拦截
  http.interceptors.request.use((config: any) => {
    // 可使用async await 做异步操作 初始化请求拦截器时，会执行此方法，此时data为undefined，赋予默认{}
    config.data = config.data || {};
    // 对应国际化资源文件后缀
    config.header['Content-Language'] = 'zh_CN';
    if (getToken()) {
      config.header['Authorization'] = 'Bearer ' + getToken();
    }
    // 是否需要加密
    const isEncrypt = (config.header || {}).isEncrypt === true;
    // 当开启参数加密
    if (isEncrypt && (config.method === 'POST' || config.method === 'PUT')) {

      // 生成一个 AES 密钥
      const aesKey = generateAesKey();
      config.header[encryptHeader] = encrypt(encryptBase64(aesKey));
      config.data = typeof config.data === 'object' ? encryptWithAes(JSON.stringify(config.data), aesKey) : encryptWithAes(config.data, aesKey);
    }

    return config;
  }, (config: any) => { // 可使用async await 做异步操作
    return Promise.reject(config);
  });
  // 响应拦截
  http.interceptors.response.use(async (response: any) => { /* 对响应成功做点什么 可使用async await 做异步操作*/

    // 加密后的 AES 秘钥
    let keyStr = null;
    if (response.header) {
      keyStr = response.header[encryptHeader];
    }
    // 加密
    if (keyStr != null && keyStr != '') {
      const data = response.data;
      // 请求体 AES 解密
      const base64Str = decrypt(keyStr);
      // base64 解码 得到请求头的 AES 秘钥
      const aesKey = decryptBase64(base64Str.toString());
      // aesKey 解码 data
      const decryptData = decryptWithAes(data, aesKey);
      // 将结果 (得到的是 JSON 字符串) 转为 JSON
      response.data = JSON.parse(decryptData);
    }
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || response.data.msg || errorCode['default'];
    //如果是401尝试刷新token
    if (code === HttpStatus.UNAUTHORIZED) {
      const [err, res] = await to(refreshToken.refreshToken(response.config));
      if (res) {
        return res;
      }
      return Promise.reject(err);
    } else if (code === HttpStatus.SERVER_ERROR) {
      modal.msg(msg);
      return Promise.reject(msg);
    } else if (code === HttpStatus.WARN) {
      modal.msg(msg);
      return Promise.reject(msg);
    } else if (code !== HttpStatus.SUCCESS) {
      modal.msg(msg);
      return Promise.reject(msg);
    } else {
      return Promise.resolve(response.data);
    }


  }, (response: any) => {
    let message = response.errMsg;
    if (message === 'Network Error') {
      message = '服务器连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常';
    } else if (message.includes('request:fail')) {
      message = '服务器连接异常';
    } else {
      message = '系统错误，请联系管理员!';
    }
    // 对响应错误做点什么 （statusCode !== 200）
    modal.msg(message);
    return Promise.reject(message);
  });
};
export {
  initRequest
};
